package com.albert.eurekaconsumer.interceptor;

/**
 * Feign请求拦截器
 *
 * @author lgl
 * @date 2020/4/21 14:12
 */

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 在发送请求前设置认证的token,
 * 1.判断本系统获取到的内部token是否过期(redis)，没有过期直接设置token,过期的话，重新去权限中心拉取token
 *
 * @author lgl
 * @date 2020-4-20 14:22:43
 */
public class FeignBasicAuthRequestInterceptor implements RequestInterceptor {

    private final static Logger logger = LoggerFactory.getLogger(FeignBasicAuthRequestInterceptor.class);


    @Autowired
    private Environment environment;

    public FeignBasicAuthRequestInterceptor() {
    }

    @Override
    public void apply(RequestTemplate template) {
        //header传递处理
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
//        Enumeration<String> headerNames = request.getHeaderNames();
//        if (headerNames != null) {
//            while (headerNames.hasMoreElements()) {
//                String name = headerNames.nextElement();
//                String values = request.getHeader(name);
//                template.header(name, values);
//            }
//        }
        String ak = environment.getProperty("consumer1.ak", "zlf");
        String sk = environment.getProperty("consumer1.sk", "sk123");
        String token = JWT.create().withAudience(ak)
                .sign(Algorithm.HMAC256(sk));
        template.header("JWT-TOKEN", token);
        logger.info("Feign  interceptor works ");
    }
}
